﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BDAlertorApp.Util
{
    class ByteBuffer
    {
        //字节缓存区
        private byte[] buf;

        //写入索引
        private int position = 0;
        private int limit;
        //缓存区字节数组的长度
        private int capacity;

        /**
         * 构造方法
         */
        private ByteBuffer(int capacity)
        {
            buf = new byte[capacity];
            this.capacity = capacity;
        }

        /**
         * 构造方法
         */
        private ByteBuffer(byte[] bytes)
        {
            buf = bytes;
            this.capacity = bytes.Length;
        }

        /**
         * 构建一个capacity长度的字节缓存区ByteBuffer对象
         */
        public static ByteBuffer Allocate(int capacity)
        {
            return new ByteBuffer(capacity);
        }

        /**
         * 构建一个以bytes为字节缓存区的ByteBuffer对象，一般不推荐使用
         */
        public static ByteBuffer Allocate(byte[] bytes)
        {
            return new ByteBuffer(bytes);
        }

        /**
         * 将bytes字节数组从startIndex开始的length字节写入到此缓存区
         */
        public void WriteBytes(byte[] bytes, int startIndex, int length)
        {
            lock (this)
            {
                int offset = length - startIndex;
                if (offset <= 0) return;
                int total = offset + position;
                for (int i = position, j = startIndex; i < total; i++, j++)
                {
                    buf[i] = bytes[j];
                }
                position = total;
            }
        }

        /**
         * 将字节数组中从0到length的元素写入缓存区
         */
        public void WriteBytes(byte[] bytes, int length)
        {
            WriteBytes(bytes, 0, length);
        }

        /**
         * 将字节数组全部写入缓存区
         */
        public void WriteBytes(byte[] bytes)
        {
            WriteBytes(bytes, bytes.Length);
        }

        /**
         * 写入一个byte数据
         */
        public void WriteByte(byte value)
        {
            lock (this)
            {
                int afterLen = position + 1;
                buf[position] = value;
                position = afterLen;
            }
        }

        /**
         * 重置
         */
        public void Reset()
        {
            position = 0;
        }

        /**
         * 获取可读的字节数组
         */
        public byte[] ToArray()
        {
            byte[] bytes = new byte[position];
            Array.Copy(buf, 0, bytes, 0, bytes.Length);
            return bytes;
        }

        /**
         * 获取缓存区大小
         */
        public int GetCapacity()
        {
            return this.capacity;
        }

        public int GetPosition()
        {
            return this.position;
        }
    }
}
